//
//  LoginVC.m
//  doubleEduStudents
//
//  Created by 盛洋 on 2021/1/4.
//  Copyright © 2021 shengYang. All rights reserved.
//

#import "LoginVC.h"
#import "RegisterVC.h"
#import "oneKeyLoginVC.h"
#import "DoneInforVC.h"

@interface LoginVC ()<UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UIView *back_view;
@property (strong, nonatomic) IBOutlet UIImageView *back_img;
@property (strong, nonatomic) IBOutlet UILabel *titleLab;//标题
@property (strong, nonatomic) IBOutlet UILabel *kindLab;//端种
@property (strong, nonatomic) IBOutlet UITextField *phoneField;//手机输入框
@property (strong, nonatomic) IBOutlet UITextField *codeField;//验证码输入框
@property (strong, nonatomic) IBOutlet UIButton *sendBtn;
@property (strong, nonatomic) IBOutlet UIButton *loginBtn;
@property (strong, nonatomic) IBOutlet UIButton *touristBtn;
@property (strong, nonatomic) IBOutlet UIView *phone_view;
@property (strong, nonatomic) IBOutlet UIView *code_view;
@property (strong, nonatomic) IBOutlet UIButton *oneKey_btn;


@end

@implementation LoginVC{
    RequestServices *service;
    int _count; // 倒计时数字
    NSTimer *_timer; // 定时器
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil backType:(int)backType
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _login_backType = backType;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];    
    [self.titleView setHidden:YES];
    [self.backKuang setHidden:YES];
    self.back_img.image = [UIImage imageNamed:@"log_center"];
    APPViewBorderRadius(self.sendBtn, 5, .5, [UIColor clearColor]);
    APPViewBorderRadius(self.phone_view, 5, .5, [UIColor colorWithHexString:Global_Border_Color]);
    APPViewBorderRadius(self.code_view, 5, .5, [UIColor colorWithHexString:Global_Border_Color]);
    self.titleLab.font = AutoLabFont1;
    [self setFont];
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(event:)];
    [self.view addGestureRecognizer:tapGesture];
        
    if (Is_iPhone) {
        NSLog(@"当前是手机登录");
    }else{
        NSLog(@"当前是平板登录");
    }
    
    self.phoneField.delegate = self;
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"输入手机号" attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:self.phoneField.font}];
    self.phoneField.attributedPlaceholder = attrString;
    
    self.codeField.delegate = self;
    NSAttributedString *attrString1 = [[NSAttributedString alloc] initWithString:@"输入验证码" attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:self.codeField.font}];
    self.codeField.attributedPlaceholder = attrString1;


    service = [[RequestServices alloc]initWithDelegate:self];
}



//添加点击手势
-(void)event:(UITapGestureRecognizer *)gesture{
    [self.view endEditing:YES];
}

-(void)setFont{
    self.kindLab.font  = self.phoneField.font = self.codeField.font = self.sendBtn.titleLabel.font =  self.touristBtn.titleLabel.font = self.oneKey_btn.titleLabel.font =  self.loginBtn.titleLabel.font = AutoLabFont2;
}

//发送验证码
- (IBAction)sendCodeBtn:(id)sender {
    [self.view endEditing:YES];
    [self.phoneField resignFirstResponder];
    if (self.phoneField.text.length != 11) {
        [self ShowNewMsg:@"请填写正确的手机号码"];
        return;
    }
    [service getMobileCode:self.phoneField.text type:@"1" tag:8000];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{  //string就是此时输入的那个字符textField就是此时正在输入的那个输入框返回YES就是可以改变输入框的值NO相反
    
    if ([string isEqualToString:@"\n"])  //按会车可以改变
    {
        return YES;
    }
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    
    if (self.phoneField == textField)  //判断是否时我们想要限定的那个输入框
    {
        if ([toBeString length] > 11) { //如果输入框内容大于11则弹出警告
            textField.text = [toBeString substringToIndex:11];
            [self ShowNewMsg:@"手机号不可超过11位"];
            return NO;
        }
    }
    if (self.codeField == textField)
    {
        if ([toBeString length] > 6) {
            textField.text = [toBeString substringToIndex:6];
            [self ShowNewMsg:@"验证码不能超过6位"];
            return NO;
        }
    }
    return YES;
}

- (void)handleTimer
{
    
    if (_count > 0) {
        [self.sendBtn setUserInteractionEnabled:NO];
        [self.sendBtn setTitle:[NSString stringWithFormat:@"%ds",_count] forState:UIControlStateNormal];
        
    } else {
        [self.sendBtn setUserInteractionEnabled:YES];
        [self.sendBtn setTitle:[NSString stringWithFormat:@"重发验证码"] forState:UIControlStateNormal];
        
        [_timer invalidate];
    }
    _count -= 1;
}


#pragma mark - requestDelegate
-(void)getFinished:(NSDictionary *)obj tag:(long long)tag{
    
    if (tag == 8000) {
        _count = 60;
        [self handleTimer];
        NSUDSetPhone(self.phoneField.text);
        _timer = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:@selector(handleTimer) userInfo:nil repeats:YES];
    }
    if (tag == 8001) {
        //loginType  0普通登录 1注册后登录
        if ([obj[@"loginType"] intValue] == 0) {
            [self SkipLogin:1];
        }else{
            DoneInforVC *vc = [[DoneInforVC alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        NSUDSetValueWithKey(obj[@"token"],@"Token");
        //登录成功添加绑定设备
        NSString *deviceName;
        if (Is_iPhone) {
            deviceName = @"iPhone";
        }else{
           deviceName = @"iPad";
        }
        [service addLoginDevice:Uuid deviceName:deviceName tag:8002];
    }
    
    if (tag == 8002) {
        NSLog(@"设备绑定成功");
    }
    
}

-(void)getError:(NSError *)error tag:(long long)tag{
    [self ShowNewMsg:error.domain];
}



//注册
- (IBAction)pushToVC:(id)sender {
    RegisterVC *vc = [[RegisterVC alloc]init];
    [self PushToViewController:vc];
}
//登录
- (IBAction)loginToVC:(id)sender {
    [self.view endEditing:YES];
    if (![self.phoneField.text CheckNSStringData]) {
           [self ShowNewMsg:@"请输入手机号"];
           return;
       }
       if (![self.codeField.text CheckNSStringData]) {
           [self ShowNewMsg:@"请输入验证码"];
           return;
       }
    [service loginToApplication:self.phoneField.text captcha:self.codeField.text messageDeviceToken:@"" tag:8001];
}

- (void)SkipLogin:(NSInteger)type
{
    [self.view endEditing:YES];
    AppDelegate *appDelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
        BaseNavVC * nav = [[BaseNavVC alloc]init];
        nav.view.backgroundColor = [UIColor whiteColor];
        appDelegate.window.rootViewController = nav;
        appDelegate.nav = nav;
}
//游客模式
- (IBAction)touristToVC:(id)sender {
     [self SkipLogin:1];
}

//一键登录
- (IBAction)oneKeyLog:(UIButton *)sender {
    oneKeyLoginVC *vc = [[oneKeyLoginVC alloc]init];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
